package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.StrategyComment;
import cn.wolfcode.wolf2w.domain.Travel;
import cn.wolfcode.wolf2w.query.StrategyCommentQuery;
import cn.wolfcode.wolf2w.repository.StrategyCommentRepository;
import cn.wolfcode.wolf2w.service.IStrategyCommentService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
//@Transactional mongodb事务必须复制集方式
public class StrategyCommentServiceImpl implements IStrategyCommentService {

    @Autowired
    private StrategyCommentRepository repository;

    @Autowired
    private MongoTemplate template;


    @Override
    public void save(StrategyComment strategyComment) {
        strategyComment.setId(null);
        strategyComment.setCreateTime(new Date());
        repository.save(strategyComment);

    }

    @Override
    public void update(StrategyComment strategyComment) {
        repository.save(strategyComment);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public StrategyComment get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<StrategyComment> list() {
        return repository.findAll();
    }

    @Override
    public Page<StrategyComment> query(StrategyCommentQuery qo) {
        Query query = new Query();

        if(StringUtils.hasLength(qo.getStrategyId())){
            query.addCriteria(Criteria.where("strategyId").is(qo.getStrategyId()));
        }
        //根据攻略评论的时间排序
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                Sort.Direction.DESC, "createTime");
        return DBHelper.query(template,pageable,query,StrategyComment.class,qo);
    }

    @Override
    public void commentThumb(String cid, String uid) {
        //查询评论对象,获取点赞用户集合
        StrategyComment comment = this.get(cid);
        List<String> uidList = comment.getThumbuplist();
        //判断当前用户id是否存在集合中
        if(!uidList.contains(uid)){
            //如果不存在,表示点赞操作 点赞数 + 1 用户id添加到集合中
            comment.setThumbupnum(comment.getThumbupnum() + 1);
            uidList.add(uid);
        }else{
            //如果存在表示取消点赞 点赞数 - 1 用户id移除出集合
            comment.setThumbupnum(comment.getThumbupnum() - 1);
            uidList.remove(uid);
        }
        //
        //comment.setThumbuplist(uidList);
        //更新
        this.update(comment);
    }
}
